#define  _CRT_SECURE_NO_WARNINGS
#include "SeqList.h"

void SLInit(SL* p)
{
	assert(p);
	p->arr = NULL;
	p->size = p->capacity = 0;
}

void print(SL* p)
{
	for (int i = 0; i < p->size; i++)
	{
		printf("%d->", p->arr[i]);
	}
	printf("\n");
}

void SLPushBack(SL* p, SLDatatype x)
{
	assert(p);
	if (p->size == p->capacity)
	{
		int newcapacity = p->capacity == 0 ? 4 : 2 * p->capacity;
		SLDatatype* tmp = (SLDatatype*)realloc(p->arr, sizeof(SLDatatype) * newcapacity);
		assert(tmp);
		p->arr = tmp;
		p->capacity = newcapacity;
	}
	p->arr[p->size++] = x;
}

void SLPushFront(SL* p, SLDatatype x)
{
	assert(p);
	if (p->size == p->capacity)
	{
		int newcapacity = p->capacity == 0 ? 4 : 2 * p->capacity;
		SLDatatype* tmp = (SLDatatype*)realloc(p->arr, sizeof(SLDatatype) * newcapacity);
		assert(tmp);
		p->arr = tmp;
		p->capacity = newcapacity;
	}
	for (int i = p->size; i > 0; i--)
	{
		p->arr[i] = p->arr[i - 1];
	}
	p->arr[0] = x;
	p->size++;
}

void SLPopBack(SL* p)
{
	assert(p);
	p->size--;
}

void SLPopFront(SL* p)
{
	assert(p);
	for (int i = 0; i < p->size - 1; i++)
	{
		p->arr[i] = p->arr[i + 1];
	}
	p->size--;
}

SLDatatype SeqFind(SL* p, SLDatatype x)
{
	assert(p);
	for (int i = 0; i < p->size; i++)
	{
		if (p->arr[i] == x)
		{
			return i;
		}
	}
	return -1;
}

void SLInsert(SL* p, SLDatatype pos, SLDatatype x)
{
	assert(p);
	if (p->size == p->capacity)
	{
		int newcapacity = p->capacity == 0 ? 4 : 2 * p->capacity;
		SLDatatype* tmp = (SLDatatype*)realloc(p->arr, sizeof(SLDatatype) * newcapacity);
		assert(tmp);
		p->arr = tmp;
		p->capacity = newcapacity;
	}
	for (int i = p->size; i > pos; i--)
	{
		p->arr[i] = p->arr[i - 1];
	}
	p->arr[pos] = x;
	p->size++;
}

void SLErase(SL* p, int pos)
{
	assert(p);
	for (int  i = pos; i < p->size - 1; i++)
	{
		p->arr[i] = p->arr[i + 1];
	}
	p->size--;
}

void SLDestroy(SL* p)
{
	assert(p);
	free(p->arr);
	p->arr = NULL;
	p->size = p->capacity = 0;
}